package com.wuliupai.delivery.wuliupaidelivery.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.ListView;

import com.wuliupai.delivery.wuliupaidelivery.R;

/**
 * Descriptions：自定义上拉加载下拉刷新
 * 继承自V4包的SwipeRefreshLayout，在原有控件刷新功能的基础上，
 * 添加了加载更多的功能
 * <p>
 * Author：ChenME
 * Date：11/26/2016
 * Email：ibelieve1210@163.com
 */
public class RefreshAndLoadLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {

    private Context mContext;
    private ProgressDialog progressDialog;

    /**
     * 滑动到最下面时的上拉操作
     */

    private int mTouchSlop;
    /**
     * ListView实例
     */
    private ListView mListView;

    /**
     * RecyclerView实例
     */
    private RecyclerView mRecyclerView;

    /**
     * 上拉监听器, 到了最底部的上拉加载操作
     */
    private OnLoadListener mOnLoadListener;

    /**
     * ListView的加载中footer
     */
    private View mListViewFooter;

    /**
     * 按下时的y坐标
     */
    private int mYDown;
    /**
     * 抬起时的y坐标, 与mYDown一起用于滑动到底部时判断是上拉还是下拉
     */
    private int mLastY;
    /**
     * 是否在加载中 ( 上拉加载更多 )
     */
    private boolean isLoading = false;

    /**
     * @param context
     */
    public RefreshAndLoadLayout(Context context) {
        this(context, null);
    }

    public RefreshAndLoadLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mListViewFooter = LayoutInflater.from(context).inflate(R.layout.listview_footer, null, false);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        // 初始化ListView对象
        if (mListView == null) {
            getListView();
        }
        if (mListView == null && mRecyclerView == null) {
            getRecyclerView();
        }
    }

    /**
     * 获取ListView对象
     */
    private void getListView() {
        int childs = getChildCount();
        if (childs > 0) {
            View childView = getChildAt(0);
            if (childView instanceof ListView) {
                mListView = (ListView) childView;
                // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
                mListView.setOnScrollListener(this);
                Log.d(VIEW_LOG_TAG, "### 找到listview");
            }
        }
    }

    private void getRecyclerView() {
        int childs = getChildCount();
        if (childs > 0) {
            View childView = getChildAt(0);
            if (childView instanceof RecyclerView) {
                mRecyclerView = (RecyclerView) childView;
                // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
                mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                    }

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        // 滚动时到了最底部也可以加载更多
                        if (canLoad()) {
                            loadData();
                        }
                    }
                });
                Log.d(VIEW_LOG_TAG, "### 找到listview");
            }
        }
    }

    /**
     * (non-Javadoc)
     *
     * @see android.view.ViewGroup#dispatchTouchEvent(MotionEvent)
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();

        switch (action) {
            case MotionEvent.ACTION_DOWN:// 按下
                mYDown = (int) event.getRawY();
                break;

            case MotionEvent.ACTION_MOVE:// 移动
                break;

            case MotionEvent.ACTION_UP:// 抬起
                mLastY = (int) event.getRawY();
                if (canLoad()) {
                    loadData();
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 是否可以加载更多，条件是：
     * 到了最底部
     * listview不在加载中,同时也不在刷新中
     * 且为上拉操作.
     *
     * @return
     */
    private boolean canLoad() {
        return isBottom() && !isLoading && !isRefreshing() && isPullUp();
    }

    /**
     * 判断是否到了最底部
     */
    private boolean isBottom() {
        if (mListView != null && mListView.getAdapter() != null) {
            return mListView.getLastVisiblePosition() == (mListView.getAdapter().getCount() - 1);
        } else if (mRecyclerView != null) {
            return (mRecyclerView.computeVerticalScrollExtent() + mRecyclerView.computeVerticalScrollOffset()
                    >= mRecyclerView.computeVerticalScrollRange());
        }
        return false;
    }

    /**
     * 判断是否正在加载数据
     *
     * @return
     */
    public boolean isLoading() {
        return isLoading;
    }

    /**
     * 是否是上拉操作
     *
     * @return
     */
    private boolean isPullUp() {
        return 0 != mLastY && (mYDown - mLastY) >= 350;
    }

    /**
     * 如果到了最底部,而且是上拉操作.那么执行onLoad方法
     */
    private void loadData() {
        if (mOnLoadListener != null) {
            // 设置状态
            setLoading(true);
            mOnLoadListener.onLoad();
        }
    }

    /**
     * @param loading
     */
    public void setLoading(boolean loading) {
        isLoading = loading;
        if (isLoading) {
            if (null != mListView) {
                mListView.addFooterView(mListViewFooter);
            } else {
                if (null == progressDialog) {
                    progressDialog = new ProgressDialog(mContext);
                }
                progressDialog.setMessage("加载中");
                progressDialog.show();
            }
        } else {
            if (null != mListView) {
                mListView.removeFooterView(mListViewFooter);
            } else {
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }
            mYDown = 0;
            mLastY = 0;
        }
    }

    /**
     * @param loadListener
     */
    public void setOnLoadListener(OnLoadListener loadListener) {
        mOnLoadListener = loadListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // 滚动时到了最底部也可以加载更多
        if (canLoad()) {
            loadData();
        }
    }

    /**
     * 加载更多的监听器
     *
     * @author mrsimple
     */
    public interface OnLoadListener {
        void onLoad();
    }
}